const { articleTable, typeTable } = require('../../schemas/index');

const { getResJson } = require('../../assets/util');

/**
 * 获取汇总信息
 * @param {Function} callback 回到函数
 */
exports.infoStatistics = callback => {
    // 获取所有文章类型
    let typeData = typeTable.find({});
    let types = [];
    typeData.exec((err, rs) => {
        let typeArr = rs.map(item => {
            types.push({
                name: item.typeName,
                value: item.articleTotal
            });
            return item.typeName
        });
        articleTable.find({}, (err, data) => {
            if (err) {
                console.log('---------');
                console.log(err);
                console.log('获取汇总数据失败');
            }
            // 汇总数据
            let resData = {
                likes: dataReduce(typeArr, data, 'likes'),
                commentTotal: dataReduce(typeArr, data, 'commentTotal'),
                readingTimes: dataReduce(typeArr, data, 'readingTimes'),
                types,
                typeArr
            }
            let resJson = getResJson(resData, '查询成功');
            callback(resJson);
        })
    })
}

exports.getArticleRanking = (params, callback) => {
    articleTable.find({}, (err, data) => {
        if (err) {
            console.log('---------');
            console.log(err);
            console.log('获取排名前十文章数据失败');
        }
        let resJson = getResJson(data, '获取成功');
        callback(resJson);
    }).limit(10).sort({
        [params.type]: -1
    })
}

/**
 * 通过字段去汇总数据
 * @param {Array} typeArr 文章类型数据
 * @param {Array} data 文章数据
 * @param {String} field 字段名
 * @return {Array} 汇总之后的数据
 */
function dataReduce(typeArr, data, field) {
    let result = data.reduce((prev, next) => {
        let result = prev.filter(item => {
            if (item.name === next.type) {
                item.value += next[field];
            }
            return item.name === next.type;
        }).length;
        if (!result) {
            prev.push({
                name: next.type,
                value: next[field]
            })
        }
        return prev;
    }, []);
    let currentTypeArr = result.map(item => item.name);
    typeArr.map(item => {
        if (!currentTypeArr.includes(item)) {
            result.push({
                name: item,
                value: 0
            })
        }
    })
    return result;
}